/*-
 * Gateway.java
 *
 * Copyright (c) 2007, Stein Gunnar Bakkeby
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Stein Gunnar Bakkeby nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.googlecode.attention.at;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import com.googlecode.attention.Communicator;
import com.googlecode.attention.CommunicatorStatus;
import com.googlecode.attention.State;
import com.googlecode.attention.util.ThreadTerminator;

import static com.googlecode.attention.ComLogStatements.*;
import static com.googlecode.attention.State.*;

/**
 * AT gateway.
 * <BR>
 * <BR>The AT gateway is backed by a BlockingQueue
 * and thus will block other threads adding new
 * ATs if the capacity is reached.
 *
 * @author Stein Gunnar Bakkeby
 */
public class Gateway implements Runnable,
                                AtListener<ConnectionReset>{

  protected final int queue_timeout = 2;
  private final BlockingQueue<AtCommand<?>> queue;
  private final Thread sender;
  private final Thread receiver;
  protected AtCommand<?> atInProgress;
  protected boolean mobileConnected;
  private State state;
  
  /**
   * This will create the AT gateway. The gateway is backed by a
   * BlockingQueue and thus will block other threads adding new
   * ATs if the capacity is reached.
   * 
   * @param capacity Maximum number of ATs to handle
   * @param comm The communication interface to use
   * @param terminator The thread terminator for this thread
   */
  public Gateway(final int capacity,
                 final Communicator comm,
                 final ThreadTerminator<?> terminator) {
    queue = new ArrayBlockingQueue<AtCommand<?>>(capacity);
    this.sender = new Thread(new Sender(comm, terminator, queue));
    this.receiver = new Thread(new Receiver(comm, terminator, sender));
    this.mobileConnected = false;
    this.state = INITIALISING;
  }
  
  /**
   * Adds an AT command to the gateway.
   * 
   * @param at The AT command to send.
   */
  public void addAT(final AtCommand<?> at) {
    try {
      at.setSender(Class.forName(new Throwable().getStackTrace()[2].getClassName()));
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
    try {
      queue.put(at);
    } catch (InterruptedException e) {
      COM_DEBUG.log(e);
    }
  }
  
  @SuppressWarnings("cast")
  public void run() {
    COM_TRACE.log("Gateway.run(): Starting");
    sender.start();
    receiver.start();
    
    ((ConnectionReset)(Object)IncomingAt.CONNECTION_RESET.getAtCommand()).addListener(this);
    state = FULLY_OPERATIONAL;
    final MobileSensor sensor = new MobileSensor();
    sensor.sense();
    COM_TRACE.log("Gateway.run(): Stopping");
  }
  
  private class MobileSensor implements AtListener<At> {
    
    private boolean hasNotifiedMobileNotConnected;
    
    public MobileSensor() {
      hasNotifiedMobileNotConnected = false;
    }
    
    public void sense() {
      final At at = new At(this);
      at.prepareTest();
      addAT(at);
    }
    
    public void atFailure(final At command) {
      mobileConnected = false;
      if (!hasNotifiedMobileNotConnected) {
        System.out.println("Mobile connected: " + mobileConnected);
        COM_DEBUG.log("Mobile connected: " + mobileConnected);
        hasNotifiedMobileNotConnected = true;
      }
      sense();
    }

    public void atSuccess(final At command) {
      mobileConnected = true;
      System.out.println("Mobile connected: " + mobileConnected);
      COM_DEBUG.log("Mobile connected: " + mobileConnected);
    }
  }
  
  public void atFailure(final ConnectionReset command) {
    this.mobileConnected = !mobileConnected;
    System.out.println("Mobile connected: " + mobileConnected);
    COM_DEBUG.log("Mobile connected: " + mobileConnected);
  }

  public void atSuccess(final ConnectionReset command) {
    this.mobileConnected = !mobileConnected;
    System.out.println("Mobile connected: " + mobileConnected);
    COM_DEBUG.log("Mobile connected: " + mobileConnected);
  }
  
  private class Receiver implements Runnable {
    
    private final ThreadTerminator<?> terminator;
    final Thread sender;
    private final Communicator comm;
    
    /**
     * Creates the internal sender object.
     * 
     * @param comm The communicator that will send and receive the command.
     * @param terminator The thread terminator that will terminate the whole
     *                   program when exiting.
     * @param queue The blocking queue to read commands (to send) from.
     */
    public Receiver(final Communicator comm,
                    final ThreadTerminator<?> terminator,
                    final Thread sender) {
      this.comm = comm;
      this.terminator = terminator;
      this.sender = sender;
    }
    
    
    public void run() {
      COM_TRACE.log("Receiver.run(): Starting");
      RUN: while (!terminator.isTerminating()) {
        String fromMobile;
        do {
          fromMobile = comm.getResponse(queue_timeout, TimeUnit.SECONDS);
          if (terminator.isTerminating()) break RUN;
        } while (fromMobile == null);
        
        // 03.07.2007 - the problem here is that the atInProgress is set to null
        // as it parses the messages one-by-one instead of as a bulk as expected.
        if (atInProgress == null) COM_DEBUG.log("AT in progress == null");
        else COM_DEBUG.log(atInProgress.getCommand());
        if (atInProgress != null) { //  && fromMobile.startsWith(atInProgress.getCommand())
          atInProgress.parse(fromMobile);
          atInProgress = null;
        } else {
          IncomingAtParser.getInstance().parse(fromMobile);
        }
//          }
//        }
        
        
        sender.interrupt();
      }
      COM_TRACE.log("Receiver.run(): Stopping");
    }
  }
  
  private class Sender implements Runnable {
    
    private final ThreadTerminator<?> terminator;
    private final BlockingQueue<AtCommand<?>> queue;
    private final Communicator comm;
    
    /**
     * Creates the internal sender object.
     * 
     * @param comm The communicator that will send and receive the command.
     * @param terminator The thread terminator that will terminate the whole
     *                   program when exiting.
     * @param queue The blocking queue to read commands (to send) from.
     */
    public Sender(final Communicator comm,
                  final ThreadTerminator<?> terminator,
                  final BlockingQueue<AtCommand<?>> queue) {
      this.comm = comm;
      this.terminator = terminator;
      this.queue = queue;
    }
    
    @SuppressWarnings("cast")
    public void run() {
      COM_TRACE.log("Sender.run(): Starting");
      AtCommand<?> tempAtCommand = null;
      RUN: while (!terminator.isTerminating()) {
        try {
          do {
            tempAtCommand = queue.poll(queue_timeout, TimeUnit.SECONDS);
            /*
             * In case the mobile has been disconnected while we've been
             * polling and something has been pushed into the queue within
             * queue_timeout, then we need to put that command back into
             * the queue and continue polling as normal.
             */
//            COM_TRACE.log("Sender.run(): " + tempAtCommand);
            if (tempAtCommand != null && !mobileConnected
                && !((Object)tempAtCommand instanceof At)) {
//              COM_TRACE.log("Sender.run(): <---");
              queue.put(tempAtCommand);
              tempAtCommand = null;
            }
            if (terminator.isTerminating()) break RUN;
          } while (tempAtCommand == null);
//          COM_TRACE.log("Sender.run(): --->");
          atInProgress = tempAtCommand;
          comm.sendAT(atInProgress.getCommand());
          while (atInProgress != null) {
            try {
              Thread.sleep(queue_timeout * 1000);
              if (atInProgress != null
               && comm.getStatus() != CommunicatorStatus.READING) {
                atInProgress.parse("ERROR");
                atInProgress = null;
              }
            } catch (InterruptedException e) {
              COM_005.log();
              if (atInProgress != null)  {
                COM_DEBUG.log("Sender.run(): Interrupted but atInProgress is not null");
                atInProgress = null;
              }
            }
            if (terminator.isTerminating()) break RUN;
          }
        } catch (InterruptedException e) {
          COM_DEBUG.log("Sender.run(): Interrupted while polling for AT commands?");
        }
      }
      COM_TRACE.log("Sender.run(): Stopping");
    }
  }
  
  public State getState() {
    if (!mobileConnected) {
      state = MOBILE_UNAVAILABLE;
    }
    return state;
  }
}


